package com.itlaobing.lifecycle;

import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;

/*
 	<servlet>
		<servlet-name>passive</servlet-name>
		<servlet-class>com.itlaobing.lifecycle.PassiveServlet</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>passive</servlet-name>
		<url-pattern>/passive/*</url-pattern>
	</servlet-mapping>
 */

@WebServlet( name = "passive" , urlPatterns = "/passive/*" )
public class PassiveServlet implements Servlet {
	
	static {
		System.out.println( "类加载阶段: " + PassiveServlet.class.getCanonicalName() );
	}
	
	private ServletConfig config ; // 声明一个ServletConfig类型的引用变量
	
	public PassiveServlet() {
		super();
		System.out.println( "Servlet实例【" + this + "】创建完毕" );
	}

	@Override
	public void init(ServletConfig config) throws ServletException {
		System.out.println( "初始化Servlet实例: " + this );
		// 将容器(比如Tomcat)通过参数传入ServletConfig实例的引用(地址)保存到实例变量中
		this.config = config ;
	}

	@Override
	public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {
		System.out.println( "Servlet实例【" + this + "】正在提供服务");
		PrintWriter w = resp.getWriter();
		w.println( "<p style='text-align:center'>" );
		w.println( LocalDateTime.now() );
		w.println( "</p>" );
	}
	
	@Override
	public void destroy() {
		System.out.println( "释放Servlet实例【" + this + "】所占用的资源，为回收该对象做准备");
	}
	
	@Override
	public ServletConfig getServletConfig() {
		// 返回实例变量config中所保存的引用(地址)
		return this.config;
	}

	@Override
	public String getServletInfo() {
		return "";
	}

}
